﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace InternetSpiderLib.Scenes.DataSavers
{
    public class XmlFileDataSaver : IDataSaver
    {
        private Random random = new Random((int)DateTime.Now.Ticks);

        public string FormatFileName { get; set; }

        public void Save(List<KeyValuePair<string, string>> datas)
        {
            if (datas == null || datas.Any() == false)
                return;

            var fileName = GetFileName();

            XmlDocument document = new XmlDocument();
            var root = document.AppendChild(document.CreateElement("XmlNetData"));

            foreach (var item in datas)
            {
                XmlNode itemNode = document.CreateElement("Item");
                itemNode.AppendChild(document.CreateElement("Name")).AppendChild(document.CreateTextNode(item.Key));
                itemNode.AppendChild(document.CreateElement("Value")).AppendChild(document.CreateTextNode(item.Value));

                root.AppendChild(itemNode);
            }

            var dir = Path.GetDirectoryName(fileName);
            if (Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }

            document.Save(fileName);
        }

        private string GetFileName()
        {
            var name = FormatFileName;

            Dictionary<string, string> formatValue = new Dictionary<string, string>
            {
                { "Random", random.Next(999999).ToString().PadLeft(6,'0') },
                { "Year", DateTime.Now.Year.ToString() },
                { "DayInYear", DateTime.Now.DayOfYear.ToString().PadLeft(3, '0') },
                { "FriendlyDay", DateTime.Now.ToString("yyyyMMdd") },
                { "FriendlyTime", DateTime.Now.ToString("HHmmss") },
                { "Month", DateTime.Now.Month.ToString().PadLeft(2, '0') },
                { "Day", DateTime.Now.Day.ToString().PadLeft(2, '0') },
            };

            foreach (var item in formatValue)
            {
                name = name.Replace($"{{Runtime:{item.Key}}}", item.Value);
            }

            return name;
        }
    }
}
